package com.kco.generate.java;

import com.kco.generate.config.ColumnsBean;
import com.kco.generate.config.TableBean;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.kco.generate.config.Utils.saveFile;

/**
 * 创建bean java文件
 * Created by 666666 on 2017/9/26.
 */
public final class CreateOther {

    public static void buildFile(TableBean tableBean) {
        String today = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
        StringBuilder sb = new StringBuilder();
        String className = tableBean.getClassName();

        for (ColumnsBean bean : tableBean.getColumnsBeans()){
            if (StringUtils.equalsAnyIgnoreCase("date", bean.getJavaType())){
                continue;
            }
            if (!bean.isNullAble() && bean.getDefaultValue() == null){
                String key = className +"."+bean.getPropertyName()+".NotEmpty";
                sb.append(key + "="+bean.getColumnComment()+"{validator.NotEmpty}\n");
            }
            if (bean.getMaxSize() >=2){
                String key = className +"."+bean.getPropertyName()+".Length";
                sb.append(key + "="+bean.getColumnComment()+"{validator.Length}\n");
            }
        }
        sb.append("\n\n");

        String comment = tableBean.getTableComment();
        String className1 = className.substring(0, 1).toLowerCase() + className.substring(1);
        sb.append("\t//查询"+comment+"信息\n" +
            "    query"+className+"ById : (id) => getRequest(`/"+className1+"/query/${id}`),\n" +
            "\t//新增"+comment+"信息\n" +
            "    insert"+className+" : (data) => postRequest(`/"+className1+"/insert`, data),\n" +
            "\t//删除"+comment+"信息\n" +
            "    delete"+className+"ById : (id) => postRequest(`/"+className1+"/delete/${id}`),\n" +
            "\t//更新"+comment+"信息\n" +
            "    update"+className+" : (id, data) => postRequest(`/"+className1+"/update/${id}`, data),\n" +
            "\t//分页查询"+comment+"信息\n" +
            "    list"+className+" : (pageNo = DEFAULT_PAGE_NO, pageSize = DEFAULT_PAGE_SIZE, searchData = {}) => postRequest(`/"+className1+"/list/${pageNo}/${pageSize}`, searchData),\n");

        saveFile("other/" + tableBean.getClassName() + "other.txt", sb.toString());
    }

}
